import { defineStore } from "pinia";
import type { editProductType,pendingOrdersType } from "@/types/index";
import Decimal from "decimal.js";
// useStore 可以是 useUser、useCart 之类的任何东西
// 编辑商品存储临时商品数据到新增商品页面
export const editSpecificProduct = defineStore("editproductId", {
  state: () => ({
    data: {} as editProductType,
    type: "001", //001表示新增商品，002表示编辑商品
  }),
});
// 存储购物车的待下单的商品数据
export const pendingOrders = defineStore("orderId", {
  state: () => ({
    data: [] as pendingOrdersType[],
  }),
  getters: {
    // 计算购物车提交的合计总价
    paymentPrice(): number {
      const res = this.data.reduce((subtotal, goodsItem) => subtotal + goodsItem.totalPrice, 0);
      return Number(new Decimal(res).toFixed(2));
    }
  },
  actions: {
    addToorder(val: pendingOrdersType) {
      // 判断是否有重复的商品提交，如果重复，只更新数量和总价
      const existingItem = this.data.find((item) => {
        return item.goods_id === val.goods_id && item.attributeId === val.attributeId;
      });
      if (existingItem) {
        // 出现重复，只更新数量和总价
        existingItem.quantity += val.quantity;
        const num1 = new Decimal(existingItem.display_price);
        const num2 = new Decimal(existingItem.quantity);
        existingItem.totalPrice = Number(num1.times(num2).toString());
        return false;
      }
      const num1 = new Decimal(val.display_price);
      const num2 = new Decimal(val.quantity);
      val.totalPrice = Number(num1.times(num2).toString());
      this.data.push(val);
    },
     // 找到数量为0的商品将他移除
    removeEmptyArrays() {
      this.data.forEach((item, index) => {
        if (item.quantity === 0) {
          this.data.splice(index, 1);
        }
      });
    },
  }
})